Introduction
In this article, we will learn about Core Data Framework and perform the first step of CRUD operations i.e Creating/Adding data into our database.
Before we start, first let's get an overview of the Core Data Framework and the Core Data Stack.
Using Core Data we can save our application's permanent data for offline use, to cache temporary data, and to add/undo functionality to our app on a single device. Through Core Data’s Data Model editor, you define your data types and relationships and generate respective class definitions.
Core Data Stack
A Core Data stack is made up of the following objects: one or more managed object contexts connected to a single persistent store coordinator which then connects to one or more persistent stores. It contains:
-
An instance of NSManagedObjectModel that describes the types, properties,, and relationships of your application.
-
An instance of NSManagedObjectContext to track the changes in your application's types.
-
An instance of NSPersistentStoreCoordinator used to save and fetch instances of your application's types.
- An instance of NSPersistentContainer to set up the model, context, and store coordinator simultaneously.
So let's create a simple application that will add our data into the database.
- Open Xcode and create a new project. Click on iOS -> Single View App.
- Name your Project, select the language as Swift, and make sure you check the box 'Use Core Data'.
- Checking the Use Core Data box will cause Xcode to generate boilerplate code for what’s known as an NSPersistentContainer in AppDelegate.swift.
- Select the desired location to save your Project.
- Now, we will design a UI on our Main.storyboard where we will enter the data that we need to insert into our database. I have created a simple UI that will take the name, age, and phone number as input.
- Connect the outlets i.e labels,textboxes, and the button to the ViewController. You can do it by opening the Assistant, selecting an outlet, press the Ctrl button, and drag it to your ViewController. Then, name your outlets.
- After creating the UI, open the .xcdatamodeld file in your Project Navigator. You will find the file as 'YourProjectName.xcdatamodeld'.
- Click on the 'Add Entity' button at the bottom. Name your Entity.
- Click on the '+' sign in the Attributes section. Name your attributes and assign their types.
- Refer to the below image.
- Next, open your ViewController and paste the following code. Make sure to add the line 'import Core Data'.
- import UIKit
- import CoreData
- class ViewController: UIViewController {
- @IBOutlet weak
- var txtPhoneNo: UITextField!@IBOutlet weak
- var txtAge: UITextField!@IBOutlet weak
- var txtName: UITextField!@IBOutlet weak
- var lblPhoneNo: UILabel!@IBOutlet weak
- var lblAge: UILabel!@IBOutlet weak
- var lblName: UILabel!override func viewDidLoad() {
- super.viewDidLoad()
-
- }
- @IBAction func btnAdd(_ sender: Any) {
-
- guard
- let appDelegate = UIApplication.shared.delegate as ? AppDelegate
- else {
- return
- }
- let managedContext = appDelegate.persistentContainer.viewContext
-
- let entity = NSEntityDescription.entity(forEntityName: "Details", in : managedContext) !
-
- let record = NSManagedObject(entity: entity, insertInto: managedContext)
-
- record.setValue(txtName.text, forKey: "name")
- record.setValue(Int16(txtAge.text!), forKey: "age")
- record.setValue(Int16(txtPhoneNo.text!), forKey: "phone")
- do {
- try managedContext.save()
- print("Record Added!")
-
- let alertController = UIAlertController(title: "Message", message: "Record Added!", preferredStyle: .alert)
- let OKAction = UIAlertAction(title: "OK", style: .default) {
- (action: UIAlertAction!) in
- }
- alertController.addAction(OKAction)
- self.present(alertController, animated: true, completion: nil)
- } catch
- let error as NSError {
- print("Could not save. \(error),\(error.userInfo)")
- }
- }
- }
- Now we are done performing the Add operation.
- Select a simulator or connect an iPhone device and run your Project.
- Enter the details and click on the Add button.
- If you have pasted the above code, then you must get an alert box displaying the message as 'Record Added!'
- Also, you can see the same message on your Xcode's output window.
- If you get the above outputs, then our data is successfully added to our database!
Hence, we have successfully performed the Create/Add operation. In my next articles, we will perform the remaining CRUD operations.